//
//  AppDelegate.m
//  YunKang
//
//  Created by leoking870 on 2017/9/24.
//  Copyright © 2017年 leoking870. All rights reserved.
//

#import "AppDelegate.h"
#import "YKBusinessViewController.h"
#import "YKMineViewController.h"
#import "YKDataViewController.h"
#import "YKHomeViewController.h"
#import "YKApproveViewController.h"
#import "YKDataPageViewController.h"
#import "APPInitManager.h"
#import "YKTabBarViewController.h"
#import "CYLTabBarController.h"
#import <UMCommon/UMCommon.h>
// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate

- (void)setupViewControllers {
    YKBusinessViewController* vc1 = [[YKBusinessViewController alloc]init];
    UINavigationController* nav1 = [[UINavigationController alloc]initWithRootViewController:vc1];
    
    YKApproveViewController* vc2 = [[YKApproveViewController alloc]init];
    UINavigationController* nav2 = [[UINavigationController alloc]initWithRootViewController:vc2];
    
//    YKHomeViewController* vc3 = [[YKHomeViewController alloc]init];
//    UINavigationController* nav3 = [[UINavigationController alloc]initWithRootViewController:vc3];
    
    YKDataPageViewController* vc4 = [[YKDataPageViewController alloc]init];
    UINavigationController* nav4 = [[UINavigationController alloc]initWithRootViewController:vc4];
    
    YKMineViewController* vc5 = [[YKMineViewController alloc]init];
    UINavigationController* nav5 = [[UINavigationController alloc]initWithRootViewController:vc5];
    
    self.tabBarController = [[YKTabBarViewController alloc]init];
    [self customizeTabBarForController:self.tabBarController];
    self.tabBarController.tabBar.backgroundColor = [UIColor tf_colorWithHexString:@"#717071"];
    [self.tabBarController setViewControllers:@[nav1, nav2, nav4, nav5]];
    
}
/**
 *  tabBarItem 的选中和不选中文字属性、背景图片
 */
- (void)customizeInterface {
    
    // 普通状态下的文字属性
    NSMutableDictionary *normalAttrs = [NSMutableDictionary dictionary];
    normalAttrs[NSForegroundColorAttributeName] = [UIColor darkGrayColor];
    normalAttrs[NSFontAttributeName] = [UIFont systemFontOfSize:12];
    // 选中状态下的文字属性
    NSMutableDictionary *selectedAttrs = [NSMutableDictionary dictionary];
    selectedAttrs[NSForegroundColorAttributeName] = TFSTYLE(buttonEnableBackgroundColor);
    selectedAttrs[NSFontAttributeName] = [UIFont systemFontOfSize:12];
    // 设置文字属性
    UITabBarItem *tabBar = [UITabBarItem appearance];
    [tabBar setTitleTextAttributes:normalAttrs forState:UIControlStateNormal];
    [tabBar setTitleTextAttributes:selectedAttrs forState:UIControlStateSelected];
    
    // 设置背景图片
    UITabBar *tabBarAppearance = [UITabBar appearance];
    [tabBarAppearance setBackgroundImage:[UIImage tf_imageWithColor:[UIColor tf_colorWithHexString:@"#F9FDFF"]]];
}
/*
 *
 在`-setViewControllers:`之前设置TabBar的属性，
 *
 */
- (void)customizeTabBarForController:(CYLTabBarController *)tabBarController {
    
    NSDictionary *dict1 = @{
                            CYLTabBarItemTitle : @"业务",
                            CYLTabBarItemImage : [[UIImage imageNamed:@"yk_business_icon"]tf_imageByTintColor:[UIColor darkGrayColor]],
                            CYLTabBarItemSelectedImage : @"yk_business_cur_icon",
                            };
    NSDictionary *dict2 = @{
                            CYLTabBarItemTitle : @"管理",
                            CYLTabBarItemImage : [[UIImage imageNamed:@"yk_approval_icon"]tf_imageByTintColor:[UIColor darkGrayColor]],
                            CYLTabBarItemSelectedImage : @"yk_approval_cur_icon",
                            };
    NSDictionary *dict3 = @{
                            CYLTabBarItemTitle : @"首页",
                            CYLTabBarItemImage : [[UIImage imageNamed:@"yk_index_icon"]tf_imageByTintColor:[UIColor darkGrayColor]],
                            CYLTabBarItemSelectedImage : @"yk_index_cur_icon",
                            };
    NSDictionary *dict4 = @{
                            CYLTabBarItemTitle : @"统计",
                            CYLTabBarItemImage : [[UIImage imageNamed:@"yk_date_icon"]tf_imageByTintColor:[UIColor darkGrayColor]],
                            CYLTabBarItemSelectedImage : @"yk_date_cur_icon",
                            };
    NSDictionary *dict5 = @{
                            CYLTabBarItemTitle : @"我的",
                            CYLTabBarItemImage : [[UIImage imageNamed:@"yk_my_icon"]tf_imageByTintColor:[UIColor darkGrayColor]],
                            CYLTabBarItemSelectedImage : @"yk_my_cur_icon",
                            };
    
    
    NSArray *tabBarItemsAttributes = @[ dict1, dict2, dict4, dict5 ];
    tabBarController.tabBarItemsAttributes = tabBarItemsAttributes;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc]init];
    [APPInitManager initAppConfig];
    
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
//        可以添加自定义categories
        
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:@"a9619b0ca0e109282d6cf127"
                          channel:@"AppStore"
                 apsForProduction:NO
            advertisingIdentifier:nil];
    
    [UMConfigure initWithAppkey:@"5b7233cbb27b0a6f70000033" channel:@"App Store"];
    
    [self setupViewControllers];
    self.window.rootViewController = self.tabBarController;
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
            self.tabBarController.register_id = registrationID;
//            [self.window.rootViewController showHint:[NSString stringWithFormat:@"registerID:%@", registrationID]];
            [[UIPasteboard generalPasteboard]setString:registrationID];
        }
        else{
            self.tabBarController.register_id = nil;
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
    
    
    [self customizeInterface];
    [self.window makeKeyAndVisible];
    
    return YES;
}



- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate
    // timers, and store enough application state information to restore your
    // application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called
    // instead of applicationWillTerminate: when the user quits.
    
    //[[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}


- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [JPUSHService registerDeviceToken:deviceToken];
}


- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"iOS6及以下系统，收到通知:%@", userInfo);
    
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"iOS7及以上系统，收到通知:%@", userInfo);
    
    
    completionHandler(UIBackgroundFetchResultNewData);
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [TFHTTPMANAER POST:@"login/getVersionNumber.htm" parameters:@{@"paramcode":@"SYS005"} cacheDuration:0 success:^(id responseObject) {
        NSDictionary *versionNumberMap = responseObject[@"versionNumberMap"];
        NSString *VERSIONNUMBER = versionNumberMap[@"VERSIONNUMBER"];
        double version = [[[NSBundle mainBundle]objectForInfoDictionaryKey:@"CFBundleShortVersionString"] doubleValue];
        if (VERSIONNUMBER.doubleValue > version) {
            [UIAlertController tf_showAlertInViewController:self.window.rootViewController withTitle:[NSString stringWithFormat:@"检测到新版本V%@",VERSIONNUMBER] message:versionNumberMap[@"REMARK"] cancelButtonTitle:@"升级" ohterButtonsTitles:nil actionsHandlerBlock:^(UIAlertAction *action) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/yun-kang-shang-cheng/id1294104083?mt=8"]];
            }];
        }
    } failure:^(id responseObject, NSError *error) {

    }];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
